﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace LL2024.Models.CommonLibraries.Services
{
    public class TaskChunkExecutor
    {
        // 定义一个委托，用于执行每个分块的任务
        public delegate Task<List<Dictionary<string, T>>> TaskDelegate<T>(List<T> chunk) where T : class;

        // 执行任务分块的方法
        public async Task<List<Dictionary<string, T>>[]> ExecuteAsync<T>(List<T> list, int chunkSize, TaskDelegate<T> taskDelegate) where T : class
        {
            // 将列表分块
            var chunkedLists = GetChunkedLists(list, chunkSize);

            // 创建任务数组
            Task<List<Dictionary<string, T>>>[] tasks = chunkedLists.Select(chunk => taskDelegate(chunk)).ToArray();

            // 等待所有任务完成并返回结果
            return await Task.WhenAll(tasks);
        }

        // 将集合进行分组的方法
        public List<List<T>> GetChunkedLists<T>(List<T> list, int chunkSize)
        {
            var chunkedLists = new List<List<T>>();

            for (int i = 0; i < list.Count; i += chunkSize)
            {
                var chunk = list.Skip(i).Take(chunkSize).ToList();
                chunkedLists.Add(chunk);
            }

            return chunkedLists;
        }
    }
}
